from spreadsheetdb import *
from spreadsheetdb.uoitdoc import *
from spreadsheetdb.uoitpage import *
import sys, os
from time import time, sleep
from datetime import datetime
import json
from optparse import OptionParser
from threading import Thread

def make_page(username, password, fetchaccounts, ver, outdir, 
              forcehtml=False,
              forceload=False, verbose=False):
  if verbose: print "Connecting to Google"
  google = GoogleSpreadsheet(username, password)
  accounts = listaccounts(google, ver)
  root = outdir
  if not fetchaccounts:
    targets = accounts
  else:
    targets = dict((x, accounts[x]) for x in fetchaccounts if accounts.get(x))

  print "[%s] Generating pages for: %s" % (
        str(datetime.now()), ", ".join('"%s"' % x for x in targets.keys()))

  for name, key in targets.items():
    outdir = os.path.join(root, name)
    if verbose: print "\tLoading Google Page:", name
    try:
      print "Loading %s" % name
      data = loadpages(google, key, os.path.join(outdir, "data.json"),
                       forcehtml=forcehtml,
                       forceload=forceload)
    except Exception, e:
      print "...skipped..."
      if verbose: print "\t\t%s" % str(e)
      continue

    if not os.path.exists(outdir):
      if verbose: print "\tMaking directory: %s" % outdir
      os.makedirs(outdir)

    print "rendering public page: %s" % name
    with open(os.path.join(outdir, "index.html"), "w") as f:
      f.write(make_public_page(data))

class LivePage(Thread):

  interval = 10 * 60 # 10 minutes

  def __init__(self, *E, **F):
    Thread.__init__(self)
    self.E = E
    self.F = F

  def run(self):

    while True:
      try:
        make_page(*self.E, **self.F)
      except Exception, e:
        print "Oops, google breakdown: %s" % str(e)
      print "...Make Page Thread sleeping for %s seconds" % (self.interval)
      sleep(self.interval)
    
if __name__ == '__main__':
  parser = OptionParser()
  parser.add_option('-u', dest='username')
  parser.add_option('-p', dest='password')
  parser.add_option('-v', dest='ver')
  parser.add_option('-o', dest='root')
  parser.add_option('-a', dest='accounts', 
                    help="comma separated list")
  parser.add_option('--force-html', dest='forcehtml', action='store_true')
  parser.add_option('--force-load', dest='forceload', action='store_true')
  parser.add_option('--live', dest='live', action='store_true')

  (opt, args) = parser.parse_args()

  if not (opt.username and opt.password and opt.ver and opt.root):
    parser.print_usage()
    sys.exit(0)

  fetchaccounts = opt.accounts.split(",") if opt.accounts else None

  F = dict(username=opt.username,
           password=opt.password,
           fetchaccounts=fetchaccounts,
           ver=opt.ver,
           outdir=opt.root,
           forcehtml=opt.forcehtml,
           forceload=opt.forceload)

  if not opt.live:
    F['verbose'] = 1
    make_page(**F)
  else:
    threads = []
    if fetchaccounts:
      for acc in fetchaccounts:
        F['fetchaccounts'] = [acc]
        threads.append(LivePage(**F))
    else:
      threads.append(LivePage(**F))

    for t in threads:
      t.start()

    for t in threads:
      t.join()
